/*
 * Copyright 2016 code_gg_boy, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.hisan.freeride.common.base;

import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.internal.LinkedTreeMap;

import com.hisan.freeride.R;
import com.hisan.freeride.common.model.ErrorModel;
import com.hisan.freeride.common.service.NetBroadcastReceiver;
import com.hisan.freeride.common.service.NetEvent;
import com.hisan.freeride.common.state.EmptyState;
import com.hisan.freeride.common.state.StateModel;
import com.hisan.freeride.common.utils.ActivityEffectUtil;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.view.AlertDialog;
import com.hisan.freeride.common.view.OnClickListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import es.dmoral.toasty.Toasty;

/**
 * 创建时间 : 2017/7/13
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：Fragment基类 ---协同stateModel处理error及重新加载操作
 */
public abstract class BaseFragment<VB extends ViewDataBinding> extends Fragment implements
        StateModel.CallBack,NetEvent,OnClickListener {
    protected StateModel mStateModel;
    protected VB mBinding;
    public AppManager appManager;
    private boolean isVisible;                  //是否可见状态
    protected boolean isPrepared;                 //标志位，View已经初始化完成。
    /**
     * 网络状态
     */
    private int netMobile;
    /**
     * 监控网络的广播
     */
    private NetBroadcastReceiver netBroadcastReceiver;
    public AlertDialog mDialog;

    public AlertDialog getmDialog(String msg, String cancel, String ok) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(msg)
                .setTopImage(R.mipmap.certification_prompt)
                .setNegativeButton(cancel, (dialog, which) ->   onCancel())
                .setPositiveButton(ok, (dialog, which) -> {
                    onCancel();
                    onOk();
                });
        mDialog = builder.create();
        mDialog = builder.create();
        return mDialog;
    }


    @Override
    public void onStart() {
        super.onStart();
        //注册广播
        if (netBroadcastReceiver == null) {
            netBroadcastReceiver = new NetBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            getActivity().registerReceiver(netBroadcastReceiver, filter);
            /**
             * 设置监听
             */
            netBroadcastReceiver.setNetEvent(this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        mBinding = getDataBinding(container, inflater);

        isVisible=true;
        isPrepared = true;
        mStateModel = new StateModel();
        mStateModel.attach(this);
        appManager = AppManager.getInstance();
        appManager.addActivity(getActivity());
        initView();//初始化view
        initEvent();//处理事件
        lazyLoad();

        return mBinding.getRoot();
    }
    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
    }

    private void isNetConnect() {
        switch (netMobile) {
            case -1://没有网络
                mStateModel.setEmptyState(EmptyState.NET_ERROR);
                break;
        }
    }

    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
            loadData(true);//加载数据
    }
    /** 如果是与ViewPager一起使用，调用的是setUserVisibleHint */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }
    protected void onVisible() {
        lazyLoad();
    }
    protected void onInvisible() {
        if (!BaseAppLication.getInstance().ispage()){
            BaseAppLication.getInstance().setIspage(true);
        }
    }
    protected abstract int getLayoutId();
    protected VB getDataBinding(ViewGroup container, LayoutInflater inflater) {
        return DataBindingUtil.inflate(inflater, this.getLayoutId(), container, false);
    }
    protected abstract void initView();

    protected abstract void initEvent();

    protected abstract void loadData(boolean isRefresh);


    @Override
    public void onOk() {}

    @Override
    public void onCancel() {
        if (mDialog!=null&&mDialog.isShowing())mDialog.dismiss();
    }

    /**
     * startActivityForResult 跳转
     */
    public void startActivityForResult(Class<? extends BaseActivity> activity, int requestCode, Bundle bundle, boolean isboolean) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), activity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        if (isboolean){
            ActivityEffectUtil.setActivityEffect(getActivity(), ActivityEffectUtil.ENTER_RIGHT_TO_LEFT);
        }else{
            ActivityEffectUtil.setActivityEffect(getActivity(), ActivityEffectUtil.ENTER_BOTTOM_TO_TOP);
        }
    }
    @CallSuper
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mStateModel != null) {
            mStateModel.detach();
        }
        OkGo.getInstance().cancelTag(this);
    }
    @Override
    public void onFailure(Throwable e) {
    }
    //关闭
    public  void finishActivity(boolean isboolean){
        // 结束Activity&从堆栈中移除
        appManager.finishActivity(getActivity(),isboolean);
    }
    @Override
    public void onReload() {
        if (!BaseAppLication.getInstance().ispage())
            BaseAppLication.getInstance().setIspage(true);
        loadData(true);
    }

    //正常弹窗
    public void showToast(String msg){
        Toasty.warning(getActivity(),msg, Toast.LENGTH_LONG).show();
    }
    //成功弹窗
    public void showSuccessToast(String msg){
        Toasty.warning(getActivity(),msg, Toast.LENGTH_LONG).show();
    }
    //失败弹窗
    public void showErrorToast(String msg){
        Toasty.warning(getActivity(),msg, Toast.LENGTH_LONG).show();

    }
    //监听网络
    public boolean isNetwork(){return NetworkUtils.isConnected();}
    public boolean isOk(Response response){
        return response.code() >= 200 && response.code() < 300;
    }
    //显示错误信息弹窗
    public void showError(Response<Object> response){
        if (!CollectionUtils.isNullOrEmpty(response.getRawResponse())) {
            try {
                if (response.code()<=400){
                    LinkedTreeMap<String,Object> maps= (LinkedTreeMap<String, Object>) response.body();
                    if (!CollectionUtils.isNullOrEmpty(maps)){
                        showErrorToast(maps.get("msg").toString());
                    }
                }else {
                    ErrorModel errorModel=  GsonUtils.GsonToBean(response.getRawResponse().body().string(),ErrorModel.class);
                    if (!CollectionUtils.isNullOrEmpty(errorModel)){
                        showErrorToast(errorModel.getMsg());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public void noData(){
        mStateModel.setEmptyState(EmptyState.EMPTY);
    }
    public void showData(){
        mStateModel.setEmptyState(EmptyState.NORMAL);
    }
    //显示错误信息显示不同错误布局
    public void showErrorView(int code){
        LogUtils.v("xxx",code);
        if (code==-1){
            mStateModel.setEmptyState(EmptyState.NET_ERROR);
        }else {
            mStateModel.setEmptyState(EmptyState.NOT_AVAILABLE);
        }
    }
}
